package set_;

import java.util.LinkedHashSet;
import java.util.Objects;

/**
 * @author DCSGO
 * @version 1.0
 * Car类（属性：name,price）
 * 如果name和price一样
 * 则认为是相同元素，就不能添加
 */

@SuppressWarnings({"all"})
public class LinkedHashSetExercise {
    public static void main(String[] args) {
        //同HashSet一样重写类的 hashCode 和 equals 方法就行
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("宝马", 888));
        linkedHashSet.add(new Car("奔驰", 999));
        linkedHashSet.add(new Car("宝马", 1000));
        linkedHashSet.add(new Car("奔驰", 999));
        System.out.println(linkedHashSet);
        /*
         [
         Car{name='宝马', price=888.0},
         Car{name='奔驰', price=999.0},
         Car{name='宝马', price=1000.0}]
         */
    }
}

class Car {
    String name;
    double price;

    @Override
    public String toString() {
        return "\nCar{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return Double.compare(car.price, price) == 0 && Objects.equals(name, car.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }
}
